import { getUserInfo as getUserInfoApi } from '@/api/user'
import { getRouters as getRoutersApi } from '@/api/login'
import router from '@/router'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setCookie, getCookie, removeCookie } from '@/utils/cookie'
import type { RouteRecordDto } from '@/api/login/types'
import type { UserDto, UserInfoDto } from '@/api/user/types'

// const token = ref('Bearer eyJhbGciOiJIUzM4NCJ9.eyJzZXNzaW9uS2V5IjoiMHZ2bG9qWEhVcmdyaUpZeUlXbGZydz09Iiwib3BlbmlkIjoib1FBQzU2ekxnUml0NE8wMEZQUlZ6ZHRPSWJuSSIsInBsYXRmb3JtIjoiQlVTSU5FU1MiLCJleHAiOjE3MTUwNDQ3ODUsImlhdCI6MTcxNDk1ODM4NX0.as0yknBucI6aWhJhNZxpLM8P4xTTPKdFfzOgRdlfrhAaf9tFEdH3dYnHc2swTS77')
const token = ref(getCookie('token'))

const userInfo = ref({} as UserDto)
const auditStatus = ref(false)
const isForbidInsure = ref(false)
const isGsc = ref(false)
const isOpenEleSign = ref(false)
const isOpenPaySalary = ref(false)
const isOpenWesure = ref(false)
const permissions = ref([] as string[]) 

const routerList = ref([] as RouteRecordDto[])

async function login(newToken?: string) {
    token.value = newToken || token.value || getCookie('token') || ''
    const result = await getUserInfoApi()
    setCookie('token', token.value)
    userInfo.value = result.user
    setUserInitData(result)
    const routersRes = await getRoutersApi()
    routerList.value = routersRes
    // avatar.value = result.avatarUrl
    // level.value = result.level
    // companyName.value = result.companyName
    // sessionStorage.setItem('token', token.value)
}


function setUserInitData(result: UserInfoDto) {

    auditStatus.value = result.auditStatus
    permissions.value = result.permissions
    isForbidInsure.value = result.isForbidInsure
    isGsc.value = result.isGsc
    isOpenEleSign.value = result.isOpenEleSign
    isOpenPaySalary.value = result.isOpenPaySalary
    isOpenWesure.value = result.isOpenWesure
}

function logout() {
    token.value = ''
    removeCookie('token')
    // sessionStorage.removeItem('token')
    router.push('/login')
}

function hasPermission(permission: string | null | undefined) {
    if (!permission) return true
    return permissions.value.includes(permission)

}


export default defineStore(
    'user',
    () => ({
        userInfo: {} as UserDto,
        auditStatus,
        isForbidInsure,
        isGsc,
        isOpenEleSign,
        isOpenPaySalary,
        isOpenWesure,
        token,
        permissions,
        hasPermission,
        login,
        logout,
        setUserInitData,
        routerList: [] as RouteRecordDto[]
    })
)
